//我的消息
exports.messageSum = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var async = require('async');
	var mysql = require('mysql');
	var client = mysql.createConnection(myDb);
	client.connect();
	client.query("use " + myDb.DbName);
		if(keycode[2]){
			console.log("SELECT id FROM  `360_member_relation`  WHERE state=1 and isView=0 and uid="+keycode[2]+" UNION ALL SELECT id FROM  `360_group_verify`  WHERE state=1 and oid="+keycode[2]+" and isView=0");
			client.query("SELECT id FROM  `360_member_relation`  WHERE state=1 and isView=0 and uid="+keycode[2]+" UNION ALL SELECT id FROM  `360_group_verify`  WHERE state=1 and oid="+keycode[2]+" and isView=0",
				function selectCb(err, returnData, fields){
					console.log(returnData.length);
					res.send(JSON.stringify({code:'1', CountNumber:returnData.length}));
				}
			)
		}
		else
			res.send(JSON.stringify({code:'2'}));
}

//我的消息列表
exports.messageList = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var async = require('async');
	var mysql = require('mysql');
	var client = mysql.createConnection(myDb);
	var list = req.body.list ? req.body.list : 1;

	if(req.body.History){
		var History = ' ';
		var ordey = ' ORDER BY  `addtime` DESC ';
	}
	else{
		var History = ' and isView=0 ';
		var ordey = ' ORDER BY  isView ASC ,`addtime` DESC ';
	}
	
	list = ""+(list*1-1)*5;
	client.connect();
	client.query("use " + myDb.DbName);
		if(keycode[2]){
			async.waterfall([
				function(callback){
					//console.log("SELECT `isView`,uid as `oid`, `state` as `type` ,`addtime` FROM  `360_member_relation`  WHERE state=1 UNION ALL SELECT `isView`,uid as `oid`,CONCAT('2','') as type,`addtime`,`state` FROM  `360_group_verify`  WHERE state<>1 order by addtime desc");
					console.log("SELECT id,uid,addtime,'1' as type,isView FROM  `360_group_verify`  WHERE state=1 " + History + " and oid="+keycode[2] + ordey + " limit "+list+",5");
					client.query("SELECT id,uid,addtime,'1' as type,isView FROM  `360_group_verify`  WHERE state=1 " + History + " and oid="+keycode[2] + ordey + " limit "+list+",5",
						function selectCb(err, returnData, fields){
							if(returnData.length){
								var groupVerifyId = "";
								for(i in returnData){
									groupVerifyId += ","+returnData[i].id;
									delete returnData[i].id;
								}
								var groupVerifyId = groupVerifyId.substring(1);
								var relationLength = 10 - returnData.length*1;
								callback(null,returnData,groupVerifyId,relationLength);
							}
							else
								callback(null,returnData,"null",5);
						}
					)
				},
				function(a1,a2,a3,callback){
					//console.log("SELECT state,uid,addtime FROM  `360_member_relation`  WHERE state<>1 and isView=0");
					//console.log("SELECT id,uid,addtime,'2' as type FROM  `360_member_relation`  WHERE state=1 and isView=0 and fid="+keycode[2]+" ORDER BY `addtime` DESC");
					console.log("SELECT id,uid,addtime,'2' as type,isView FROM  `360_member_relation`  WHERE state=1 "+History+" and fid="+keycode[2]+ ordey + " limit "+list+","+a3);
					client.query("SELECT id,uid,addtime,'2' as type,isView FROM  `360_member_relation`  WHERE state=1 "+History+" and fid="+keycode[2]+ ordey + " limit "+list+","+a3,
						function selectCb(err, returnData, fields){
							if(returnData.length){
								var memberRelationId = "";
								for(i in returnData){
									memberRelationId += ","+returnData[i].id;
									delete returnData[i].id;
								}
								var memberRelationId = memberRelationId.substring(1);
								if(a1.length){
									for(i in a1)
										returnData[returnData.length] = a1[i];
									callback(null,returnData,a2,memberRelationId);
								}
								else
									callback(null,returnData,a2,memberRelationId);
							}
							else{
								var memberRelationId = "null";
								callback(null,returnData,a2,memberRelationId);
							}
						}
					)
				},	
				function(b1,b2,b3,callback){
					console.log(b1);
					console.log(b2);
					console.log(b3);
					b1.sort(bojby('addtime'));
					var data = {};
					data.code = "1";
					data.data = b1.length ? b1 : [];
						client.query("UPDATE `360_group_verify` SET  `isView` =  '1' WHERE  `id` in ("+b2+") ;",
							function selectCb(err, returnUp, fields){
								//console.log(returnUp);
								client.query("UPDATE `360_member_relation` SET  `isView` =  '1' WHERE `id` in ("+b3+") ;",
									function selectCb(err, returnUp, fields){
										console.log(returnUp);
									}
								)
							}
						)
					res.send(JSON.stringify(data));
				}],
				function (err, result) {
					return;
				}
			)
		}
		else
			res.send(JSON.stringify({code:'2'}));
}

//发送消息
exports.pointSend= function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	console.log(keycode);
	var keycode = keycode.split('|');
	var fid = req.body.fid*1;
	var content = req.body.content;
	var theTime = parseInt((new Date()).valueOf()/1000);
	var async = require('async');
		if(keycode[2] && fid && content){
			var MongoClient = require('mongodb').MongoClient;
			MongoClient.connect("mongodb://localhost:27017/weimi", function(err, db) {
				if(db){
					db.collection("360_p2p_message", function (err,collection) {
						collection.insert({uid:keycode[2]*1,nickName:keycode[3],fid : fid,content:content,addtime:theTime}, function (err,row) {
							if(row.result.n)
								res.send(JSON.stringify({code:'1'}));
							else
								res.send(JSON.stringify({code:'2'}));
						})
					})
				}
				else
					res.send(JSON.stringify({code:'2'}));
			})
		}
		else
			res.send(JSON.stringify({code:'2'}));
}


//消息阅读
exports.pointRead = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var fid = req.body.fid*1;
	var list = req.body.list ? req.body.list*1 : 0;
	var theTime = parseInt((new Date()).valueOf()/1000);
	var mysql = require('mysql');
		if(keycode[2] && fid){
			var async = require('async');
			async.waterfall([
				//查询最后阅读时间
				function(callback){
					var client = mysql.createConnection(myDb);
					client.connect();
					client.query("use " + myDb.DbName);
					client.query('SELECT * FROM  `360_member_relation` where ((`uid` = '+keycode[2]+' and `fid` = '+fid+') or (`uid` = '+fid+' and `fid` = '+keycode[2]+')) and `state`=2 limit 1',
						function selectCb(err, returnData){
							if(!err){
								if(returnData[0].fid){
									if(keycode[2]==returnData[0].uid)
										callback(null,{vtime:returnData[0].uViewTime,class:"u",relationId:returnData[0].id});
									else
										callback(null,{vtime:returnData[0].fViewTime,class:"f",relationId:returnData[0].id});
								}
								else{
									res.send(JSON.stringify({code:'2'}));
								}
							}
						}
					)	
				},
				//返回消息数据
				function(a1 , callback){
					console.log(a1.vtime);
					var MongoClient = require('mongodb').MongoClient;
					var n = req.body.list*1;
					//if(n<=1)
					//	var where = {$or: [{uid:keycode[2]*1 , fid:fid , addtime:{$gt: a1.vtime*1}}, {uid:fid , fid:keycode[2]*1 , addtime:{$gt: a1.vtime*1}}]};
					//else
					//	var where = {$or: [{uid:keycode[2]*1 , fid:fid , addtime:{$lt: a1.vtime*1}}, {uid:fid , fid:keycode[2]*1 , addtime:{$lt: a1.vtime*1}}]};
					MongoClient.connect("mongodb://localhost:27017/weimi", function(err, db) {
						if(db){			//最新消息
							if(n<=1){
								db.collection("360_p2p_message", function (err,collection) {
									collection.find({$or: [{uid:keycode[2]*1 , fid:fid , addtime:{$gt: a1.vtime*1}}, {uid:fid , fid:keycode[2]*1 , addtime:{$gt: a1.vtime*1}}]},{fid:true ,content: true, addtime: true,nickName:true,_id:false}, {sort: [['addtime', 'asc']]}).toArray(function(err,row){
										if(row){
											a1.data = row;
											callback(null,a1);
										}	
										else
											res.send(JSON.stringify({code:'2'}));
									})
								})
							}
							else{			//历史消息
								db.collection("360_p2p_message", function (err,collection) {
									collection.find({$or: [{uid:keycode[2]*1 , fid:fid , addtime:{$lt: a1.vtime*1}}, {uid:fid , fid:keycode[2]*1 , addtime:{$lt: a1.vtime*1}}]},{fid:true ,content: true, addtime: true,nickName:true,_id:false}, {sort: [['addtime', 'asc']]}).limit(10).skip((n-2)*10).toArray(function(err,row){
										if(row){
											a1.data = row;
											callback(null,a1);
										}	
										else
											res.send(JSON.stringify({code:'2'}));
									})
								})								
							}
						}
						else
							res.send(JSON.stringify({code:'2'}));
					})			
				},
				function(b1 , callback){
					var client = mysql.createConnection(myDb);
					client.connect();
					client.query("use " + myDb.DbName);
					client.query("UPDATE `360_member_relation` SET  `"+b1.class+"ViewTime` =  '"+theTime+"' WHERE  `id` ="+b1.relationId+" LIMIT 1 ;",
						function selectCb(err, returnData){
							if(!err)
								res.send(JSON.stringify({code:'1',data:b1.data}));
							else
								res.send(JSON.stringify({code:'2'}));
						}
					)					
				}],
				function (err, result) {
						return false;
				}
			)
		}
		else
			res.send(JSON.stringify({code:'2'}));
}


//群组消息发送
exports.groupSend = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var theTime = parseInt((new Date()).valueOf()/1000);
	var uid = keycode[2]*1;
	var gid = req.body.gid*1;
	var content = req.body.content;
	var async = require('async');
	var mysql = require('mysql');
	var client = mysql.createConnection(myDb);
		client.connect();
		client.query("use " + myDb.DbName);
		if(gid && uid){
			async.waterfall([
				//判断是否是群成员
				function(callback){
					client.query('SELECT `id` FROM  `360_group_member` where `gid` = ' + gid + ' and `uid` = '+ uid +' limit 1',
						function selectCb(err, data , fields){
							if(data.length)
								callback(null,true);
							else
								res.send(JSON.stringify({code:'2'}));
						}
					)
				},
				function(a1,callback){
					var MongoClient = require('mongodb').MongoClient;
					MongoClient.connect("mongodb://localhost:27017/weimi", function(err, db) {
						if(db){
							db.collection("360_group_message", function (err,collection) {
								collection.insert({uid:uid,nickName:keycode[3],gid : gid,content:content,addtime:theTime}, function (err,row) {
									if(row.result.n)
										res.send(JSON.stringify({code:'1'}));
									else
										res.send(JSON.stringify({code:'2'}));
								})
							})
						}
						else
							res.send(JSON.stringify({code:'2'}));
					})
				},			
				function(b1,callback){
					
				}],		
				function (err, result){
					return;
				}
			)
		}
		else
			res.send(JSON.stringify({code:'2'}));
}





//群消息查看
exports.groupRead = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var gid = req.body.gid*1;
	var list = req.body.list ? req.body.list*1 : 0;
	var theTime = parseInt((new Date()).valueOf()/1000);
	var mysql = require('mysql');
		if(keycode[2] && gid){
			var async = require('async');
			async.waterfall([
				//查询最后阅读时间
				function(callback){
					var client = mysql.createConnection(myDb);
					client.connect();
					client.query("use " + myDb.DbName);
					client.query('SELECT `ViewTime` , `id` as `vid` FROM  `360_group_member` where `uid` = '+keycode[2]+' and `gid` = '+gid+' limit 1',
						function selectCb(err, returnData){
							if(!err){
								if(returnData.length)
									callback(null,{vtime:returnData[0].ViewTime,vid:returnData[0].vid});
								else
									res.send(JSON.stringify({code:'2'}));
							}
							else
								res.send(JSON.stringify({code:'2'}));
						}
					)					
				},
				//返回消息数据
				function(a1 , callback){
					var MongoClient = require('mongodb').MongoClient;
					var n = req.body.list*1;
					console.log(n);
					MongoClient.connect("mongodb://localhost:27017/weimi", function(err, db) {
						if(db){				//最新消息
							if(n<=1){
								db.collection("360_group_message", function (err,collection) {
									collection.find({uid:keycode[2]*1 , gid:gid , addtime:{$gt: a1.vtime*1}},{fid:true ,content: true, addtime: true,nickName:true,_id:false}, {sort: [['addtime', 'asc']]}).toArray(function(err,row){
										if(row){
											a1.data = row;
											callback(null,a1);
										}
										else
											res.send(JSON.stringify({code:'1',data:[]}));
									})
								})
							}
							else{			//历史消息
								db.collection("360_group_message", function (err,collection) {
									collection.find({uid:keycode[2]*1 , gid:gid , addtime:{$lt: a1.vtime*1}},{fid:true ,content: true, addtime: true,nickName:true,_id:false}, {sort: [['addtime', 'asc']]}).limit(10).skip((n-2)*10).toArray(function(err,row){
										if(row){
											a1.data = row;
											callback(null,a1);
										}
										else
											res.send(JSON.stringify({code:'1',data:[]}));
									})
								})			
							}
						}
						else
							res.send(JSON.stringify({code:'2'}));
					})		
				},
				function(b1 , callback){
					var client = mysql.createConnection(myDb);
					client.connect();
					client.query("use " + myDb.DbName);
					client.query("UPDATE `360_group_member` SET  `" + "ViewTime` =  '"+ theTime +"' WHERE  `id` ="+b1.vid+" LIMIT 1 ;",
						function selectCb(err, returnData){
							if(!err)
								res.send(JSON.stringify({code:'1',data:b1.data}));
							else
								res.send(JSON.stringify({code:'1',data:[]}));
						}
					)	
				}],
				function (err, result) {
					return;
				}
			)
		}
		else
			res.send(JSON.stringify({code:'2'}));	
}
